package com.zry.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.code.kaptcha.Constants;
import com.zry.VO.UserVO;
import com.zry.constant.KConstant;
import com.zry.entity.User;
import com.zry.service.user.IUserService;
import com.zry.utils.pwd.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author Zry
 */
@Controller
public class LoginController {

    @Autowired
    private IUserService userService;

    @GetMapping("/login")
    public String login(HttpSession session){
        // 判断用户登录信息
        User user = (User) session.getAttribute(KConstant.SESSION_USER);
        if(user!=null){
            return "redirect:/";
        }

        return "login";
    }

    @PostMapping("/logined")
    @ResponseBody
    public String toLogin(@RequestBody UserVO userVO, HttpSession session){

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getTelephone, userVO.getAccount());

        User user = userService.getOne(queryWrapper);
        if(user==null){
            return "fail";
        }

        // 验证码校验
        String code = userVO.getCode();
        String sessionCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if(!code.equalsIgnoreCase(sessionCode)){
            return "failCode";
        }

        // 将用户输入的密码进行加密
        String password = MD5Util.md5slat(userVO.getPassword());
        // 与数据库已经加密的密码进行比对
        if(user.getPassword().equals(password)){
            session.setAttribute(KConstant.SESSION_USER,user);
            return "success";
        }

        return "fail";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){

        session.invalidate();

        return "redirect:/login";
    }


}
